<template>
  <div class="userInfo">
    <el-card>
      <el-descriptions class="margin-top" title="个人信息" :column="2" border :contentStyle="rowCenter"
                       :labelStyle="rowCenter">
        <!--按钮-->
        <template slot="extra">
          <el-button type="primary" plain @click="handleUpdate(userInfo)">编辑信息</el-button>
          <el-button type="danger" plain @click="handleDelete(userInfo)">注销账号</el-button>
        </template>

        <!--头像信息-->
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-camera-solid"></i>
            &nbsp;
            &nbsp;
            <b>个人头像</b>
          </template>
          <img class="img" :src="userInfo.avatar" alt=""/>
        </el-descriptions-item>

        <!--用户名-->
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            &nbsp;
            &nbsp;
            <b>登录账户</b>
          </template>
          {{ userInfo.username }}
        </el-descriptions-item>

        <!--用户编号-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="id"></svg-icon>
            &nbsp;
            &nbsp;
            <b>用户编号</b>
          </template>
          {{ userInfo.id }}
        </el-descriptions-item>


        <!--电话号-->
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-phone"></i>
            &nbsp;
            &nbsp;
            <b>电话号码</b>
          </template>
          {{ userInfo.phone }}
        </el-descriptions-item>


        <!--性别-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="gender"></svg-icon>
            &nbsp;
            &nbsp;
            <b>用户性别</b>
          </template>
          <!--男-->
          <svg-icon icon-class="man" v-if="userInfo.gender == 0" style="height: 20px;width: 20px"></svg-icon>
          <!--女-->
          <svg-icon icon-class="woman" v-if="userInfo.gender == 1" style="height: 20px;width: 20px"></svg-icon>
        </el-descriptions-item>

        <!--账号状态-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="status"></svg-icon>
            &nbsp;
            &nbsp;
            <b>账号状态</b>
          </template>
          <!--正常-->
          <svg-icon icon-class="normal" v-if="userInfo.status == 0" style="height: 30px;width: 30px"></svg-icon>
          <!--封禁-->
          <svg-icon icon-class="banned" v-if="userInfo.status == 1" style="height: 30px;width: 30px"></svg-icon>
        </el-descriptions-item>

        <!--生日-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="birthday"></svg-icon>
            &nbsp;
            &nbsp;
            <b>用户生日</b>
          </template>
          {{ userInfo.birthday }}
        </el-descriptions-item>


        <!--角色-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="role"></svg-icon>
            <b>角色信息</b>
          </template>
          <el-tag v-if="userInfo.roleId == 1" type="success">管理员</el-tag>
          <el-tag v-if="userInfo.roleId == 2" type="danger">普通用户</el-tag>
        </el-descriptions-item>

        <!--VIP状态-->
        <el-descriptions-item>
          <template slot="label">
            <svg-icon icon-class="vip"></svg-icon>
            &nbsp;
            &nbsp;
            <b>会员状态</b>
          </template>
          <!--会员-->
          <svg-icon icon-class="isVIP" v-if="userInfo.isVip" style="height: 50px;width: 60px"></svg-icon>
          <!--非会员-->
          <svg-icon icon-class="isNotVIP" v-if="!userInfo.isVip" style="height: 50px;width: 60px"></svg-icon>
        </el-descriptions-item>

        <!--注册日期-->
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-date"></i>
            &nbsp;
            &nbsp;
            <b>注册日期</b>
          </template>
          {{ userInfo.registerTime }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>


    <!-- 修改个人信息 -->
    <el-dialog title="修改个人信息" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" name="img" :action="uploadURL" :show-file-list="false"
                     :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="token">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div style="font-size:xx-small;">点击上传头像，只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="电话号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号"/>
        </el-form-item>
        <el-form-item label="用户性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option :key="'0'" label="男" :value="'0'"/>
            <el-option :key="'1'" label="女" :value="'1'"/>
          </el-select>
        </el-form-item>
        <el-form-item label="用户生日">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"
                          format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteUser, getInfo, updateUserInfo} from "@/api/user.js";

export default {
  name: "Info",
  data() {
    return {
      token: {
        token: ''
      },
      uploadURL: 'http://localhost:9999/admin/upload',
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 是否显示弹出层
      open: false,
      userInfo: null,
      rowCenter: {
        "text-align": "center"
      }
    };
  },
  mounted() {
    this.getUserInfo();
    this.token.token = this.$store.getters.token
  },
  methods: {
    getUserInfo() {
      getInfo()
        .then((res) => {
          this.userInfo = res.data
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /**
     * 注销按钮
     * @param id
     */
    handleDelete(user) {
      this.$alert('是否确认注销用户:"' + user.username + '"的数据？', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') { // 只在用户点击了"确定"按钮时执行删除和注销操作
            deleteUser(user.id)
              .then(() => {
                this.$notify({
                  title: '操作成功',
                  message: '注销用户成功！',
                  type: 'success'
                });
                // 退出登录
                this.$store.dispatch('user/logout');
                this.$router.push(`/login?redirect=${this.$route.fullPath}`);
              })
              .catch(() => {
                this.$notify({
                  title: '操作失败',
                  message: '注销用户数据时出现错误。',
                  type: 'error'
                });
              });
          }
        }
      });
    },

    /**
     * 修改按钮操作
     * @param userInfo
     */
    handleUpdate(userInfo) {
      this.reset()
      getInfo(userInfo.id).then((response) => {
        this.form = response.data
        this.open = true
      })
    },
    /**
     * 取消按钮
     */
    cancel() {
      this.open = false
      this.reset()
    },

    /**
     * 表单重置
     */
    reset() {
      this.form = {}
    },
    /**
     * 提交按钮
     */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          updateUserInfo(this.form).then((response) => {
            this.$notify({
              title: '操作成功',
              message: '修改个人信息成功！',
              type: 'success'
            });
            this.open = false
            //刷新页面
            window.location.reload()
          })
        }
      })
    },
    // 图片上传成功回调
    handleAvatarSuccess(res) {//上传封面
      if (res.code === 200) {
        this.form.avatar = res.data
        this.$notify({
          title: '操作成功',
          message: '图书封面上传成功',
          type: 'success'
        })
      } else {
        this.$notify.error({
          title: '操作失败',
          message: '图书封面上传失败，请稍后重试！'
        })
      }
    },
    beforeAvatarUpload(file) {//判断头像大小
      const isJPG = file.type == 'image/png' || file.type == 'image/jpg' || file.type == 'image/jpeg';
      //file.size / 1024 / 1024 表示将文件大小从字节转换为MB。< 10 表示判断文件大小是否小于10MB
      const isLt2M = file.size / 1024 / 1024 < 10;
      // console.log(file);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped>
.userInfo {
  height: 100%;
  margin: 20px 10px 20px 10px;
}

.img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar {
  margin-left: 100px;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}
</style>
